const { Service } = require('egg');
const { tableToList } = require('../utils/tools');

/**
 * 节次合并
 * @param {string[]} table 周空闲教室
 */
const mergeDuring = table => {
  const need = {};
  for (let i = 1; i <= 11; i++) {
    if (i % 2 === 0) continue;
    for (let j = i + 1; j <= 12; j++) {
      if (j % 2 !== 0) continue;
      need[`${i}-${j}`] = [];
    }
  }

  for (let i = 1; i <= table.length; i++) {
    for (const e of table[i - 1]) {
      let do_ = false;
      for (let j = i + 1; j <= table.length; j++) {
        const index = table[j - 1].indexOf(e);
        if (index === -1) {
          need[`${i * 2 - 1}-${(j - 1) * 2}`].push(e);
          do_ = true;
          break;
        }
        table[j - 1].splice(index, 1);
      }
      if (!do_) {
        need[`${i * 2 - 1}-${table.length * 2}`].push(e);
      }
    }
  }

  const result = {};
  for (const key in need) {
    if (need[key].length !== 0) result[key] = need[key];
  }
  result['上午'] = result['1-4'] || [];
  result['下午'] = result['5-8'] || [];
  result['晚上'] = result['9-12'] || [];
  result['全天'] = result['1-12'] || [];

  delete result['1-4'];
  delete result['5-8'];
  delete result['9-12'];
  delete result['1-12'];

  return result;
};

module.exports = class emptyroomService extends Service {
  /**
   * @param {string} term 学期
   * @param {string} zc 周次
   * @param {string} week 星期
   * @param {{label:string, value:string}} jxl 教学楼
   * @param {string} school_id 校区id
   * @return {object} *
   */
  async table(term, zc, week, jxl, school_id) {
    const Cookie = this.ctx.state.Cookie;
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbxx/kxjs_Querydata`;
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        typewhere: 'jszq',
        xnxqh: term,
        zc,
        zc2: zc,
        xq: week,
        xq2: week,
        jxqbh: '',
        jxlbh: jxl.value,
        jsbh: '',
        bjfh: '=',
        rnrs: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 20000,
    });
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#kbtable');
        const tem = [];
        tableList.forEach((e, i) => {
          if (i > 1 && i !== tableList.length - 1) tem.push(tableList[i][1].split('，').filter(item => item !== ''));
        });
        return {
          campus_id: this.ctx.state.campusId,
          school_id,
          zc,
          week,
          building: jxl.label,
          data: mergeDuring(tem),
        };
      } catch (err) {
        throw err;
      }
    }
    return {};
  }
};
